<script setup lang="ts">
import { graphic } from 'echarts/core'

import { computed, onMounted, shallowRef } from 'vue'

import useEcharts, { type EChartsOption } from '~/composables/chart'
import BlockHead from './block-head.vue'

import defaults from './default-chart-option'

import type { ProductInfo } from '../type'

defineOptions({
  name: 'ItemThree',
})

const props = defineProps<{
  data: ProductInfo
}>()

const { chartRef, setOption } = useEcharts()

const data = shallowRef<{ name: string, value: string, yoy: string }[]>([])
const option = computed<EChartsOption>(() => {
  return {
    tooltip: {
      ...defaults.tooltip,
    },
    legend: {
      data: ['销售额', '同期值'],
      top: 20,
      left: 'center',
    },
    grid: {
      ...defaults.grid,
      bottom: 20,
      right: 40,
    },
    yAxis: {
      type: 'category',
      inverse: true,
      data: data.value.map(v => v.name),
      axisLabel: {
        interval: 0,
        formatter(value: string) {
          // 限制显示前6个字符，超出部分用省略号表示
          return value.length > 6 ? `${value.substring(0, 6)}...` : value
        },
      },
    },
    xAxis: {
      type: 'value',
      splitNumber: 2,
      axisLabel: {
        show: true,
      },
    },
    series: [
      {
        name: '销售额',
        type: 'bar',
        barWidth: 7,
        data: data.value.map(v => v.value),
        itemStyle: {
          color: new graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2E89FA' },
            { offset: 1, color: '#9EC6F8' },
          ]),
        },
      },
      {
        name: '同期值',
        type: 'bar',
        barWidth: 7,
        data: data.value.map(v => v.yoy),
        itemStyle: {
          color: new graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#3CB254' },
            { offset: 1, color: '#A6EFAE' },
          ]),
        },
      },
    ],
  }
})

onMounted(() => {
  data.value = props.data.map((v) => {
    return {
      name: v.name,
      value: v.value1,
      yoy: v.value2,
    }
  })
  setOption(option.value)
})
</script>

<template>
  <div class="w-full flex flex-auto flex-col">
    <BlockHead title="产品销售排名TOP10" />
    <div class="block-body h-96 w-full flex-auto">
      <div ref="chartRef" style="width:100%;height:100%;" />
    </div>
  </div>
</template>
